package org.an.proj.contacts.net.imageload;

import android.content.Context;
import android.net.Uri;
import android.support.annotation.IdRes;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Request;
import com.squareup.picasso.RequestHandler;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import org.an.proj.contacts.MyApplication;

// 自定义 RequestHandler

/**
 * 自定义Picasso RequestHandler 根据Schema,取本地Drawable目录下的图片
 */
public class ResRequestHandler extends RequestHandler {

  public static final String URL_SCHEMA_APP = "app";
  public static final String URL_SCHEMA_HTTP = "http";
  public static final String URL_SCHEMA_HTTPS = "https";

  /**
   * 检查是否能处理请求
   *
   * @param data data.uri.getScheme()
   */
  @Override public boolean canHandleRequest(Request data) {
    return URL_SCHEMA_HTTP.equals(data.uri.getScheme()) ||
      URL_SCHEMA_HTTPS.equals(data.uri.getScheme()) ||
      URL_SCHEMA_APP.equals(data.uri.getScheme());
  }

  @Override public Result load(Request request, int networkPolicy) throws IOException {
    Uri uri = request.uri;
    InputStream is = null;
    if (URL_SCHEMA_APP.equals(uri.getScheme())) {
      String packageName = uri.getHost();
      int versionCode = uri.getPort();
      // 通过文件名取本地drawable目录下图片资源
      int resId = get(MyApplication.getInstance(), uri.getPath());
    }
    return new Result(is, Picasso.LoadedFrom.DISK);
  }

  private @IdRes int get(Context context, String res) {
    try {
      Class<?> aClass = Class.forName(context.getPackageName() + ".R$style");
      Field file = aClass.getField(res);
      int style = file.getInt(res);
      return style;
    } catch (Exception e) {
      e.printStackTrace();
      return 0;
    }
  }
}